package com.example.origin.spider.utils;

import cn.hutool.json.JSONUtil;
import com.aliyun.ocr20191230.Client;
import com.aliyun.ocr20191230.models.RecognizeCharacterAdvanceRequest;
import com.aliyun.ocr20191230.models.RecognizeCharacterResponse;
import com.aliyun.ocr20191230.models.RecognizeCharacterResponseBody;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@UtilityClass
public class OcrUtil {

    public List<String> verifyCodes(File file) {

        try (InputStream inputStream = Files.newInputStream(file.toPath())) {
            return verifyCodes(inputStream);
        } catch (Exception e) {
            log.error("verifyCodes error",e);
        }
        return new ArrayList<>();
    }
    public List<String> verifyCodes(byte[] bytes) {
        try (InputStream inputStream =  new ByteArrayInputStream(bytes)) {
            return verifyCodes(inputStream);
        } catch (Exception e) {
            log.error("verifyCodes error",e);
        }
        return new ArrayList<>();
    }
    private static List<String> verifyCodes(InputStream inputStream) throws Exception {

        // "YOUR_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_SECRET" 的生成请参见：https://help.aliyun.com/document_detail/175144.html
        // 如果您是用的子账号AccessKey，还需要为子账号授予权限AliyunVIAPIFullAccess，请参见：https://help.aliyun.com/document_detail/145025.html
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId("LTAI5tMuSMDoph7E97xg4Fts")
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret("g6WazvLWKEJ53iT6QDpYPqe5D4hsXO");
        // 访问的域名
        config.endpoint = "ocr.cn-shanghai.aliyuncs.com";
        Client client = new Client(config);

        RecognizeCharacterAdvanceRequest request = new RecognizeCharacterAdvanceRequest()
                .setImageURLObject(inputStream).setMinHeight(10).setOutputProbability(true);
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.setReadTimeout(10000000);
        // 复制代码运行请自行打印 API 的返回值
        log.info("RecognizeCharacterAdvanceRequest：{}" , JSONUtil.toJsonStr(request));
        RecognizeCharacterResponse response = client.recognizeCharacterAdvance(request, runtime);
        log.info("RecognizeCharacterResponse：{}" , JSONUtil.toJsonStr(response));
        if (response != null && response.getStatusCode() == 200) {
            RecognizeCharacterResponseBody body = response.getBody();
            RecognizeCharacterResponseBody.RecognizeCharacterResponseBodyData data = body.getData();
            List<RecognizeCharacterResponseBody.RecognizeCharacterResponseBodyDataResults> results = data.getResults();
            List<String> list = results.stream().map(e -> {
                String s = e.getText();
                StringBuilder sb = new StringBuilder();
                for (char c : s.toCharArray()) {
                    if (c != ' ') {
                        sb.append(c);
                    }
                }
                return sb.toString();
            }).collect(Collectors.toList());
            log.info("codes：{}" , JSONUtil.toJsonStr(list));
            return list;
        }
        return new ArrayList<>();
    }

    @SneakyThrows
    public List<String> verifyCodes(URL url, Map<String,String> properties)  {
        URLConnection urlConnection = url.openConnection();
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            urlConnection.addRequestProperty(entry.getKey(),entry.getValue());
        }
        try (InputStream inputStream = urlConnection.getInputStream()){
           return verifyCodes(inputStream);
        } catch (Exception e) {
            log.error("verifyCodes error",e);
        }
        return new ArrayList<>();
    }

    public List<String> verifyCodes(URL url)  {
        try (InputStream inputStream = url.openConnection().getInputStream()){
            return verifyCodes(inputStream);
        } catch (Exception e) {
            log.error("verifyCodes error",e);
        }
        return new ArrayList<>();
    }

}
